package package1;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.LinkedList;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class TestForDownload {
	@SuppressWarnings("unused")
	public static void main(String[] args) throws IOException, Exception {
		System.err.println("start");
		String fileName;
		String name;
		
		name = "2015.12.13 0929 量尺寸的跳舞.MP4";
		String url = "http://mvvideo2.meitudata.com/566cc9f90e6551333.mp4";
		
		fileName = "D:\\美拍视频\\vivian\\"+name;
		if(new File(fileName).exists())
			throw new IOException(fileName+" already existed");
		downloadMP4(url,fileName);
		System.err.println("over");
		open(fileName);
//		open("D:\\美拍视频\\vivian");
//		String fileName = "C:/Users/wangyic/Desktop/baidu.html";
//		fileName = "C:\\Users\\User\\Desktop\\123.html";
//		String website = "http://www.baiddu.com";
//		downloadToFile(website, fileName);
//		showURLInformation(url);
//		String sr = sendPost(website, "key=123&v=456");
//		System.out.println(sr);
//		downloadTest();
//		downloadQIDSSyncTest();
	}

	public static void open(String string) throws IOException {
		java.awt.Desktop.getDesktop().open(new File(string));
	}
	public static void open(File b) throws IOException {
		open(b.getAbsolutePath());
	}

	private static void downloadMP4(String urlAddress, String fileName) throws IOException {
		URL url = new URL(urlAddress);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		InputStream is = con.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[]b = new byte[1024];
		int len;
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(fileName)));
		while ((len = bis.read(b)) != -1)
			bos.write(b, 0, len);
		bos.close();
		bis.close();
	}

	private static void downloadQIDSSyncTest()
			throws MalformedURLException, IOException, UnsupportedEncodingException, FileNotFoundException {
		String qidsURL = null;
		qidsURL = "http://www.baidu.com";
		qidsURL = "https://www.google.com";
		qidsURL = "https://ext-webserv-corona.houston.hp.com/QuoteIds/1.8/quoteServices/searchQuote/html/quotes?queryParams=qtnNr:E000427887";

		URL url = new URL(qidsURL);
		InetSocketAddress isa = new InetSocketAddress("web-proxy.corp.hp.com", 8080);
		Proxy proxy = new Proxy(Proxy.Type.HTTP, isa);
		// System.getProperties().put("proxySet", "true");
		// System.getProperties().put("proxyHost", "web-proxy.corp.hp.com");
		// System.getProperties().put("proxyPort", "8080");
		System.err.println("11111");
		URLConnection con = null;
		con = url.openConnection();
		con = url.openConnection(proxy);
		System.err.println("2222");
		// trustAllHttpsCertificates();
		System.err.println("33333");
		// HttpsURLConnection.setDefaultHostnameVerifier(hv);
		System.err.println("4444");

		// String author = new sun.misc.BASE64Encoder().encode(("bmi"+ ":" +
		// "1qaz2wsx_prod").getBytes());
		// con.setRequestProperty("Authorization", "Basic " + author);

		InputStream is = con.getInputStream();
		System.err.println("5555");
		InputStreamReader isr = new InputStreamReader(is, "utf-8");
		BufferedReader br = new BufferedReader(isr);
		String temp;
		StringBuffer sb = new StringBuffer();
		System.err.println("begin to write!");
		while ((temp = br.readLine()) != null)
			sb.append("\n" + temp);
		File f = new File("C:/Users/wangyic/Desktop/qids.html");
		FileOutputStream fos = new FileOutputStream(f);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
		BufferedWriter bw = new BufferedWriter(osw);
		bw.write(sb.toString());
		br.close();
		bw.flush();
		bw.close();
		System.err.println(sb);
		System.err.println("***success***");
	}

	public static HostnameVerifier hv = new HostnameVerifier() {
		public boolean verify(String urlHostName, SSLSession session) {
			System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
			return true;
		}
	};

	@SuppressWarnings("unused")
	private static void trustAllHttpsCertificates() throws Exception {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	}

	static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}

	@SuppressWarnings("unused")
	private static void downloadTest() throws Exception {
		String content = DownloadWebsite();
		// String result = extractText(content,"�?","�?");
		// System.err.println(result);
		String a = "abcdaefga";
		String i = extractText(a, null, null);
		System.err.println(i);
		System.err.println(a);

		download("www.baidu.com");
		String temp = extractText();
		System.err.println(temp);
	}

	private static LinkedList<String> list = new LinkedList<String>();
	private static String currentContent = null;

	public static void selectText(String text, String begin, String end) throws Exception {
		list.add(currentContent = extractText(text, begin, end));
	}

	public static void deselectText() throws Exception {
		if (list.size() > 0)
			list.removeLast();
		else
			throw new Exception("you don't have any text selected");
	}

	public static void deselectAll() throws Exception {
		list.clear();
	}

	public static String extractText(String a, String a1, String a2) throws Exception {
		if (a1 == null)
			a1 = "";
		if (a2 == null)
			return a.substring(a.indexOf(a1) + a1.length());
		String begin = "aa";
		begin = a1;
		int beginLeng = begin.length();
		String end = "aa";
		end = a2;
		if (!a.contains(begin))
			throw new Exception("Begin text \"" + begin + "\" could not be found!");
		int beginPosition = a.indexOf(begin) + beginLeng;
		String b = a.substring(beginPosition + 1);
		if (!b.contains(end))
			throw new Exception("End text \"" + end + "\" could not be found!");
		int endIndex = b.indexOf(end);
		int endPosition = beginPosition + endIndex + 1;
		String s = a.substring(beginPosition, endPosition);
		return s;
	}

	public static String extractText() throws Exception {
		return extractText(currentContent, null, null);
	}

	public static void download(String urlString) throws Exception {
		if (!urlString.toLowerCase().contains("http"))
			urlString = "https://" + urlString;
		URL url = new URL(urlString);
		URLConnection con = url.openConnection();
		BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
		String buf;
		StringBuffer sb = new StringBuffer();
		while ((buf = br.readLine()) != null)
			sb.append("\r" + buf);
		currentContent = sb.toString();
		br.close();
	}

	private static String DownloadWebsite() throws MalformedURLException, IOException, UnsupportedEncodingException {
		String urlAddress = "https://www.baidu.com";
		URL url = new URL(urlAddress);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		InputStream is = con.getInputStream();
		String buf;
		InputStreamReader isr = new InputStreamReader(is, "utf-8");
		BufferedReader br = new BufferedReader(isr);
		StringBuffer sb = new StringBuffer();
		while ((buf = br.readLine()) != null)
			sb.append("\r" + buf);
		System.err.println(sb);
		String temp = sb.toString();
		return temp;
	}

	public static void downloadToFile(String website, String fileName) throws Exception {
		URLConnection con = new URL(website).openConnection();
		InputStream is = con.getInputStream();
		InputStreamReader isr = new InputStreamReader(is, "gb2312");
		BufferedReader br = new BufferedReader(isr);
		String temp;
		StringBuffer sb = new StringBuffer();
		while ((temp = br.readLine()) != null)
			sb.append("\n" + temp);
		File f = new File(fileName);
		FileOutputStream fos = new FileOutputStream(f);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "gb2312");
		BufferedWriter bw = new BufferedWriter(osw);
		bw.write(sb.toString());
		br.close();
		bw.flush();
		bw.close();
		System.err.println(sb);
		System.err.println("***success***");
	}

	public static String sendPost(String url, String param) throws IOException {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Users\\User\\Desktop\\123.html")))); 
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// special setting for the post request
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// get output stream from the connection
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			InputStream is = conn.getInputStream();
//			BufferedInputStream bis = new BufferedInputStream(is);
//			InputStreamReader isr = new InputStreamReader(bis,Charset.forName("gb2312"));
//			in = new BufferedReader(isr);
			in = new BufferedReader(new InputStreamReader(is, "gb2312"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line + "\r";
				bw.write(result);
				bw.flush();
			}
		} catch (Exception e) {
			System.err.println("error stack:" + e);
			e.printStackTrace();
		}
		// close IO in finally
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				bw.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	@SuppressWarnings("unused")
	private static void showURLInformation(URL url) throws IOException, URISyntaxException {
		System.err.println("getAuthority:" + url.getAuthority());
		System.err.println("getDefaultPort:" + url.getDefaultPort());
		System.err.println("getFile:" + url.getFile());
		System.err.println("getHost:" + url.getHost());
		System.err.println("getPath:" + url.getPath());
		System.err.println("getPort:" + url.getPort());
		System.err.println("getProtocol:" + url.getProtocol());
		System.err.println("getQuery:" + url.getQuery());
		System.err.println("getRef:" + url.getRef());
		System.err.println("getUserInfo:" + url.getUserInfo());
		System.err.println("getContent:" + url.getContent());
		System.err.println("toString:" + url.toString());
		System.err.println("toURI:" + url.toURI());
	}
	private static String getDesktop() {
		return System.getenv("USERPROFILE") + "\\desktop\\";
	}
}
